<template>
  <a-modal
    :title="title"
    :open="visible"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="公司名称" name="companyName">
        <a-input v-model:value="form.companyName" placeholder="请输入公司名称" />
      </a-form-item>

      <a-form-item label="法人名称" name="legalPerson">
        <a-input v-model:value="form.legalPerson" placeholder="请输入法人名称" />
      </a-form-item>

      <a-form-item label="客户名称" name="customerName">
        <a-input v-model:value="form.customerName" placeholder="请输入客户名称" />
      </a-form-item>

      <a-form-item label="联系电话" name="phone">
        <a-input v-model:value="form.phone" placeholder="请输入联系电话" />
      </a-form-item>

      <a-form-item label="客户来源" name="source">
        <a-select v-model:value="form.source" placeholder="请选择客户来源">
          <a-select-option v-for="item in customerSourceOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="客户等级" name="level">
        <a-select v-model:value="form.level" placeholder="请选择客户等级">
          <a-select-option v-for="item in customerLevelOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="进展阶段" name="progressStage">
        <a-select v-model:value="form.progressStage" placeholder="请选择进展阶段">
          <a-select-option v-for="item in customerProgressStageOptions" :key="item.value" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue'
import type { Customer } from '@/types/customer'
import { customerSourceOptions, customerLevelOptions, customerProgressStageOptions } from '@/types/customer'
import * as customerApi from '@/api/customer'

interface Props {
  visible: boolean
  formData?: Partial<Customer>
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: () => ({})
})

const emit = defineEmits<Emits>()

// 表单相关
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<Partial<Customer>>({
  customerId: undefined,
  companyName: '',
  legalPerson: '',
  customerName: '',
  phone: '',
  source: undefined,
  level: undefined,
  progressStage: undefined
})

// 表单标题
const title = computed(() => {
  return props.formData.customerId ? '编辑客户' : '新增客户'
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请选择客户来源', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择客户等级', trigger: 'change' }
  ],
  progressStage: [
    { required: true, message: '请选择进展阶段', trigger: 'change' }
  ]
}

// 监听formData变化，填充表单
watch(() => props.formData, (newVal) => {
  if (newVal) {
    // 使用 Object.assign 确保所有字段都被正确赋值，包括 customerId
    Object.assign(form, {
      customerId: newVal.customerId,
      companyName: newVal.companyName || '',
      legalPerson: newVal.legalPerson || '',
      customerName: newVal.customerName || '',
      phone: newVal.phone || '',
      source: newVal.source,
      level: newVal.level,
      progressStage: newVal.progressStage
    })
  } else {
    // 重置表单
    Object.assign(form, {
      customerId: undefined,
      companyName: '',
      legalPerson: '',
      customerName: '',
      phone: '',
      source: undefined,
      level: undefined,
      progressStage: undefined
    })
  }
}, { immediate: true, deep: true })

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    formRef.value?.resetFields()
  }
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    if (form.customerId) {
      // 编辑：调用更新接口
      await customerApi.updateCustomer({ ...form, customerId: form.customerId })
    } else {
      // 新增：调用新增接口
      await customerApi.addCustomer(form)
    }

    message.success(`${title.value}成功`)
    emit('success')
  } catch (error) {
    message.error(`${title.value}失败`)
    console.error(`${title.value}失败:`, error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script>